package cn.edu.web.service;

import cn.edu.web.dao.mapper.BikeMapper;
import cn.edu.web.pojo.Bike;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.NearQuery;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Transactional
@Service
public class BikeServiceImpl implements BikeService {

	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Autowired
	private BikeMapper bikeMapper;
	
	@Override
	public Bike getById(Long id) {
		return bikeMapper.getById(id);
	}

	@Override
	public List<Bike> findAll() {
		//调用mongo的模板查找数据，然后将数据
		return mongoTemplate.findAll(Bike.class);
	}

	@Override
	public void updateBikeStatus(long id, int status, String desc) {
		// 修改单车状态
		Query query = new Query().addCriteria(Criteria.where("_id").is(id));
		Update update = new Update().set("status",status).set("desc",desc);
		mongoTemplate.upsert(query, update,"bikes");
	}

	@Override
	public void save(Bike Bike) {
		mongoTemplate.save(Bike);
	}

	@Override
	public void deleteByIds(Long[] ids) {
		for (Long id : ids) {
			mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), "bikes");
		}
	}

	@Override
	public void update(Bike bike) {
		Query query = new Query().addCriteria(Criteria.where("_id").is(bike.getId()));
		Update update = new Update().set("status",bike.getStatus()).set("desc",bike.getDesc());
		mongoTemplate.upsert(query, update,"bikes");
	}

	@Override
	public GeoResults<Bike> findNear(double longitude, double latitude) {
		//传入当前的经纬度以及半径单位
		NearQuery nearQuery = NearQuery.near(longitude, latitude).maxDistance(new Distance(0.15,Metrics.KILOMETERS));
		//查找附件两百米的未使用的单车，要求只显示最近的10辆
		nearQuery.query(new Query().addCriteria(Criteria.where("status").is(0)).limit(8));
		//GeoReslut封装了要查找的单车数据，还封装了距离
		GeoResults<Bike> bikes = mongoTemplate.geoNear(nearQuery, Bike.class,"bikes");

		return bikes;
	}

	@Override
	public long findMaxId() {
//		long len = mongoTemplate.count(new Query(),"bikes");
		Bike bike = mongoTemplate.findOne(new Query().with(new Sort(new Sort.Order(Sort.Direction.DESC, "_id"))), Bike.class, "bikes");
		System.out.println(bike.getId());
		return bike.getId()+1;
	}
}
